package cn.sylinx.common.ext.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import cn.sylinx.common.ext.log.GLog;

/**
 * 获取bean实例
 * 
 * @author han
 *
 */
public class AppContextHolder implements ApplicationContextAware {

	private static ApplicationContext applicationContext = null;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

		GLog.info("ApplicationContextHolder 初始化开始...");
		if (AppContextHolder.applicationContext == null) {
			AppContextHolder.applicationContext = applicationContext;
		}
		GLog.info("ApplicationContextHolder 初始化结束。");

	}

	// 获取applicationContext
	public static ApplicationContext get() {
		return applicationContext;
	}

	public static <T> T getApplicationConfig(String config, Class<T> targetType) {
		return applicationContext.getEnvironment().getProperty(config, targetType);
	}

	// 通过name获取 Bean.
	public static Object getBean(String name) {
		return get().getBean(name);
	}

	// 通过class获取Bean.
	public static <T> T getBean(Class<T> clazz) {
		return get().getBean(clazz);
	}

	// 通过name,以及Clazz返回指定的Bean
	public static <T> T getBean(String name, Class<T> clazz) {
		return get().getBean(name, clazz);
	}

}
